package com.cs543.j.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import android.util.Log;

public class TCPClient {
	SocketAddress m_address;

	public TCPClient() {
		Thread t = new Thread(new Runnable() {
			
			public void run() {
				try {
					m_address = new InetSocketAddress("143.248.96.155", 11701);
					Log.i("TCPClient" , "Address to server : " + m_address.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		});
		t.start();
	}

	// Add a user
	public void register(String p_name) {
		String msg = "";
		Socket m_socket;
		try {
			
			Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
			InetAddress targetAddress = null;
			while(en.hasMoreElements() )
			{
				NetworkInterface each = en.nextElement();
				Enumeration<InetAddress> addressList = each.getInetAddresses();
				while(addressList.hasMoreElements() )
				{
					InetAddress eachAddress = addressList.nextElement();
					Log.i("TCPClient" , "Possible IP address : " + eachAddress.getHostAddress());
					if( !eachAddress.isLoopbackAddress() && eachAddress.getAddress().length == 4 )
					{
						targetAddress = eachAddress;
					}
				}
			}
			
			Log.i("TCPClient","Register Address : " + targetAddress.getHostAddress() );
			msg = "REGISTER;" + p_name + ";" + targetAddress.getHostAddress() + ";";

			m_socket = new Socket();
			m_socket.setTcpNoDelay(true);
			m_socket.setKeepAlive(true);
			m_socket.connect(m_address, 20000);
			sendTCPMsg(msg, m_socket);
			m_socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Get user list
	public Map<String, String> get() {
		String msg = "GET;";
		String resp;
		String[] respSplit;
		int size = -1;
		long time;
		Map<String, String> map = new HashMap<String, String>();
		
		Socket m_socket;

		// Send request
		try {
			m_socket = new Socket();
			m_socket.setTcpNoDelay(true);
			m_socket.setKeepAlive(true);
			m_socket.connect(m_address, 20000);
			sendTCPMsg(msg, m_socket);
			time = System.currentTimeMillis() + 10000; // 10sec
			while (size != 0 && time > System.currentTimeMillis() && !m_socket.isClosed() ) {
				resp = receiveTCPMsg(m_socket);
				// Initiate the number of responses remaining
				if (resp.startsWith("LIST;")) {
					respSplit = resp.split(";");
					size = Integer.parseInt(respSplit[1]) - map.size();
				}
				// Set the map
				else if (resp.startsWith("LISTELMT;")) {
					respSplit = resp.split(";");
					map.put(respSplit[1], respSplit[2]);
					if (size != -1)
						size--;
				}
			}
			m_socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.d("TCPClient", "Retrieve client # : " + map.size());
		return map;
	}

	protected void sendTCPMsg(String p_msg, Socket m_socket) {
		try {
			DataOutputStream out = new DataOutputStream(m_socket.getOutputStream());
			out.writeBytes(p_msg);
			out.flush();
		} catch (Exception e) {
		}
	}

	protected String receiveTCPMsg(Socket m_socket) {
		byte[] data = new byte[512];
		String resp;
		try {
			DataInputStream in = new DataInputStream(m_socket.getInputStream());
			in.read(data, 0, data.length);
		} catch (Exception e) {
			e.printStackTrace();
		}
		resp = new String(data, 0, data.length);

		return resp;
	}

}
